package com.cntcdt.api.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.quartz.JobExecutionException;

import com.cntcdt.api.utils.timer.job.WeixinOpenPlatformJob;

public class WXGZHPushMessageUtils implements Runnable {
		public static String post(String strURL, String params) {  
	        LogUtils.log.info(strURL);  
	        LogUtils.log.info(params);  
	        try {  
	            URL url = new URL(strURL);// 创建连接  
	            HttpURLConnection connection = (HttpURLConnection) url  
	                    .openConnection();  
	            connection.setDoOutput(true);  
	            connection.setDoInput(true);  
	            connection.setUseCaches(false);  
	            connection.setInstanceFollowRedirects(true);  
	            connection.setRequestMethod("POST"); // 设置请求方式  
	            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
	            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
	            connection.connect();  
	            OutputStreamWriter out = new OutputStreamWriter(  
	                    connection.getOutputStream(), "UTF-8"); // utf-8编码  
	            out.append(params);  
	            out.flush();  
	            out.close();  
	            // 读取响应  
	            int length = (int) connection.getContentLength();// 获取长度  
	            LogUtils.log.info(connection+"");
	            InputStream is = connection.getInputStream();  
	            if (length != -1) {  
	                byte[] data = new byte[length];  
	                byte[] temp = new byte[512];  
	                int readLen = 0;  
	                int destPos = 0;  
	                while ((readLen = is.read(temp)) > 0) {  
	                    System.arraycopy(temp, 0, data, destPos, readLen);  
	                    destPos += readLen;  
	                }  
	                String result = new String(data, "UTF-8"); // utf-8编码  
	                LogUtils.log.info(result);  
	                return result;  
	            }  
	        } catch (IOException e) {  
	            // TODO Auto-generated catch block  
	            return "";
	        }  
	        return ""; // 自定义错误信息  
	    }
		
		String content =  "";
		String touser = "";
		int messageType = 0;
		String title = "";
		String description = "";
		String messageUrl = "";
		String picurl = "";
		
		String borrowTime = "";
		String terminal = "";
		String money = "";
		String taskId = "";
		String remark = "";
		String cdb = "";
		
		String returnTime = "";
		String address = "";
		String leaseLong = "";
		String consume = "";
		String value = "";
		
		String firstData = "";
		
		public WXGZHPushMessageUtils(Map<String,Object> data){
			
			this.messageType =Integer.valueOf(String.valueOf(data.get("messageType")));
			this.touser = data.get("touser").toString();
			if(messageType == 1){
				this.content = data.get("content").toString();
			}
			else if(messageType == 2){
//				this.content = data.get("content").toString();
				this.title = data.get("title").toString();
				this.description =  data.get("description").toString();
				this.messageUrl =  data.get("messageUrl").toString();
				this.picurl =  data.get("picurl").toString();
			}
			else if(messageType == 3){
				this.borrowTime = data.get("borrowTime").toString();
				this.terminal = data.get("terminal").toString();
				this.money = data.get("money").toString();
				this.taskId = data.get("taskId").toString();
				this.remark = data.get("remark").toString();
				this.cdb = data.get("cdb").toString();
				this.value = data.get("value").toString();
			}
			else if(messageType == 4){
				this.firstData = data.get("firstData").toString();
				this.returnTime = data.get("returnTime").toString();
				this.address = data.get("address").toString();
				Double consumeMoney = Double.valueOf(String.valueOf(data.get("consume")));
				BigDecimal b2 = new BigDecimal(consumeMoney);
				this.consume = b2.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue()+"元";
				this.leaseLong = data.get("leaseLong").toString();
				Double userMoney = Double.valueOf(String.valueOf(data.get("remark")));
				BigDecimal b = new BigDecimal(userMoney);
				this.remark = "可提现来电余额为："+b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue()+"元。";
				this.cdb = data.get("cdb").toString();
			}
		}
		
		@Override
		public void run() {
			if(!WeixinOpenPlatformJob.weixinOpenPlatformToken.equals("")){
				if(messageType == 1){
					String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinOpenPlatformJob.weixinOpenPlatformToken;
					String prems = "{\"touser\":\""+touser+"\",\"msgtype\":\"text\",\"text\":{\"content\":\""+content+"\"}}";
					post(url,prems);
				}
				else if (messageType == 2){
					String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinOpenPlatformJob.weixinOpenPlatformToken;
					String prems = "{ \"touser\":\""+touser+"\",\"msgtype\":\"news\",\"news\":{\"articles\": [ {\"title\":\""+title+"\",\"description\":\""+description+"\",\"url\":\""+messageUrl+"\",\"picurl\":\""+picurl+"\" } ]}}";
					post(url,prems);
				}
				else if(messageType == 3){
					String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+WeixinOpenPlatformJob.weixinOpenPlatformToken;
					String prems = " {\"touser\":\""+touser+"\",\"template_id\":\"sM0Xccl9AXF8fWGut2U4G2a2ySINHzRmyFt0AMbyrNg\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbc92da7e712a95fd&redirect_uri=http%3a%2f%2fwx.imlaidian.com%2fcdt%2fuserCenter&response_type=code&scope=snsapi_base&state=1#wechat_redirect\",\"data\":{\"first\": {\"value\":\"充电宝已借入成功！\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\""+cdb+"\",\"color\":\"#173177\" },\"keyword2\": {\"value\":\""+borrowTime+"\",\"color\":\"#173177\"},\"keyword3\": {\"value\":\""+money+"\",\"color\":\"#173177\" },\"keyword4\": {\"value\":\""+value+"\",\"color\":\"#173177\" },\"keyword5\": {\"value\":\""+taskId+"\",\"color\":\"#173177\" },\"remark\":{\"value\":\""+remark+"\",\"color\":\"#173177\"} }}";
					post(url,prems);
				}
				else if(messageType == 4){
					String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+WeixinOpenPlatformJob.weixinOpenPlatformToken;
					String prems = " {\"touser\":\""+touser+"\",\"template_id\":\"r0f83hECng083ztdF_ObQ5pVKzfcqySvZEFdwZOhS74\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbc92da7e712a95fd&redirect_uri=http%3a%2f%2fwx.imlaidian.com%2fcdt%2fuserCenter&response_type=code&scope=snsapi_base&state=1#wechat_redirect\",\"data\":{\"first\": {\"value\":\""+firstData+"\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\""+cdb+"\",\"color\":\"#173177\" },\"keyword2\": {\"value\":\""+returnTime+"\",\"color\":\"#173177\"},\"keyword3\": {\"value\":\""+address+"\",\"color\":\"#173177\" },\"keyword4\": {\"value\":\""+leaseLong+"\",\"color\":\"#173177\" },\"keyword5\": {\"value\":\""+consume+"\",\"color\":\"#173177\" },\"remark\":{\"value\":\""+remark+"\",\"color\":\"#173177\"} }}";
					post(url,prems);					
				}
			}
		}
		
		public static void main(String args[]){
			WeixinOpenPlatformJob job = new WeixinOpenPlatformJob();
			try {
				job.execute(null);
			} catch (JobExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			CdtUserModel user = CdtUserDao.getInstance().findByPrimaryKey(1000060340);
//			Map map = job.weiXinServerGetUserInfo(user.getWxGZHOpenId());
			String url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+WeixinOpenPlatformJob.weixinOpenPlatformToken;
			String prems = " {\"button\":[{	\"type\":\"view\",\"name\":\"附近网点\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbc92da7e712a95fd&redirect_uri=http%3a%2f%2fwx.imlaidian.com%2fcdt%2fnearbyShop&response_type=code&scope=snsapi_base&state=1#wechat_redirect\"},{\"name\":\"借充电宝\",\"sub_button\":[{	\"type\":\"view\", \"name\":\"租借充电宝\", \"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbc92da7e712a95fd&redirect_uri=http%3a%2f%2fwx.imlaidian.com%2fcdt%2fborrowCDB&response_type=code&scope=snsapi_base&state=1#wechat_redirect\" }, {\"type\":\"view\",\"name\":\"购买数据线\", \"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbc92da7e712a95fd&redirect_uri=http%3a%2f%2fwx.imlaidian.com%2fcdt%2fborrowCDB&response_type=code&scope=snsapi_base&state=2#wechat_redirect\" }] },{\"type\":\"view\",\"name\":\"提现押金\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbc92da7e712a95fd&redirect_uri=http%3a%2f%2fwx.imlaidian.com%2fcdt%2fuserCenter&response_type=code&scope=snsapi_base&state=1#wechat_redirect\"}]}";
			post(url,prems);
		}
}
